package pers.cz.testNg;

import pers.cz.excel.PoiUtils;
import pers.cz.model.TestCase;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.List;

/**
 * @program: PostGirl-panent
 * @description: TestNg
 * @author: Cheng Zhi
 * @create: 2021-03-01 19:22
 **/
public class TestNg2 {

    private MultipartFile file;

/*    public void initFile(MultipartFile file) {
        this.file = file;
    }*/

    /**
     * 执行案例前初始化参数
     */
  //  @BeforeTest
    @DataProvider(name = "dbconfig")
    public Object[][] init() throws IOException {

        List<TestCase> listCases = this.returnTestCaeList();
        Object[][] objects = new Object[listCases.size()][];
        for (int i=0; i<listCases.size(); i++) {
            Object[] o = new Object[2];
            o[0] = listCases.get(i).getRequest();
            o[1] = listCases.get(i).getExpectedResponse();

            objects[i] = o;
        }
        return objects;
    }
    /**
     * 测试用例
     */
    @Test(dataProvider = "dbconfig")
    public void testCase(String request, String response) {
        // 发送请求
        String result = getResult(request);

        Assert.assertEquals(response,result);
    }

    /**
     * 发送请求并获取结果
     * @param request
     * @return
     * @throws IOException
     */
    private String getResult(String request) {

        HttpPost post = new HttpPost("http://10.9.238.220:19006/com.cmcc.sh.boss.interfaces.forcrm");
        // 设置header部分信息
        post.setHeader("content-type","application/json");

        StringEntity entity = new StringEntity(request,"utf-8");
        entity.setContentType("application/json");
        post.setEntity(entity);

        // 测试执行
        String result = "";
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
        try {
            HttpResponse response  = defaultHttpClient.execute(post);
            result = EntityUtils.toString(response.getEntity(),"utf-8");
            System.out.println("-------------" + result);
        } catch (Exception e) {

        }

        return result;
    }

    /**
     * 解析excel并返回TestCase集合
     * @return
     */
    public List<TestCase> returnTestCaeList() throws IOException {

        Cache cache = Cache.getCache();
        MultipartFile file = cache.getMap().get("test");
        List<TestCase> listCases = PoiUtils.excelToEntity(file,1001);

        return listCases;
    }
}
